package omm.domain.comparativegraph;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import omm.domain.CommissionStrategy;

public class BarGraphicStrategy extends GraphicStrategy {

	private String urlBarFormat ="http://chart.apis.google.com/chart?chs=300x280" +
			"&amp;chd=t:%s" +
			"&amp;cht=bhg&amp;chco=7371c4&amp;chxt=x,y,x" +
			"&amp;chxl=0:|%s" +
			"1:|%s" +
			"2:||%%" +
			"&amp;chg=%d,0,3,3";
	
//	private String urlBarFormat ="http://chart.apis.google.com/chart?chs=300x280" +
//	"&amp;chd=t:%s" +
//	"&amp;cht=bhg&amp;chco=7371c4&amp;chxt=x,y,x" +
//	"&amp;chxl=0:|%s" +
//	"1:|%s" +
//	"2:||%%" +
//	"&amp;chg=%d,0,3,3";
//	
	/**
	 * Calcula el maximo que debera tener el eje Y
	 * 
	 * @param periodsValue
	 *            Map con clave numero de periodo y valor de cada periodo
	 */
	private Integer calculateMaxXAxis(Map<String, Integer> periodsValue) {
		Iterator<Integer> iterator = periodsValue.values().iterator();
		Integer maxValue = 0;
		while (iterator.hasNext()) {
			Integer actualValue = iterator.next();
			if (maxValue < actualValue) {
				maxValue = actualValue;
			}
		}
		int om = 1;
		if (maxValue > 0) {
			while (om <= maxValue) {
				om *= 10;
			}
			om /= 10;
		} else {
			maxValue = 0;
		}

		// maximo redondeado a la magnitud obtenida
		Integer maxYAxis = (int) ((maxValue % om == 0) ? Math.ceil(maxValue) : maxValue - (maxValue % om)
				+ om);
		return maxYAxis;
	}

	private String calculateGraphicPercentages(Map<String, Integer> percentages, Integer maxAxis) {
		Map<String, Integer> graphicPercentages = new HashMap<String, Integer>();
		for (Map.Entry<String, Integer> e : percentages.entrySet()) {
			Integer numero =(int) Math.round(e.getValue() * 100 / maxAxis);
			graphicPercentages.put(e.getKey(), (int) Math.round(e.getValue() * 100 / maxAxis));
		}
		return percentagesToString(graphicPercentages);
	}
	
	
	private String calculateXAxis(Integer maxXAxis) {
		String axis = "";
		for (Integer i = 0; i<= maxXAxis; i+=10){
			axis += i.toString() + '|';
		}
		return axis;
	}
	
	private String calculateNames(Map<String, Integer> percentages) {
		String names = "";
		for (Map.Entry<String, Integer> e : percentages.entrySet()) {
			names = e.getKey() + '|' + names ;
		}
		return names;
	}
	
	@Override
	public String getGraphicURL(Map<String, Double> data, CommissionStrategy commissionStrategy) {
		
		Map<String, Integer> percentages = calculatePercentages(data);
		Integer maxXAxis = calculateMaxXAxis(percentages);
		String strPercentages = calculateGraphicPercentages(percentages,maxXAxis);
		String axis = calculateXAxis(maxXAxis);
		String names = calculateNames(percentages);
		
		Integer grid = 10;
		Object[] params = {strPercentages, axis, names, grid};

		return String.format(urlBarFormat, params);
	}

		
}
